# Create your views here.
from django.shortcuts import render_to_response
from django.shortcuts import HttpResponseRedirect
from registration.views import register
from registration.forms import RegistrationForm
from SampleTracker.sample_tracker.models import Sample
from SampleTracker.sample_tracker.forms import SampleForm
from django.template import RequestContext
from django.shortcuts import get_object_or_404


def home(request):
    """
    Display the home page
    """
    
    mycontext=RequestContext(request)
    form = RegistrationForm(data=request.POST, files=request.FILES)
    return register(request, success_url='registration_complete.html',
             form_class=RegistrationForm, profile_callback=None,
             template_name='sample_tracker/home.html',
             extra_context=None)


def show_sample_details(request, sample_id):
    """
    Display sample details
    """
    sample = get_object_or_404(Sample, pk=sample_id)
    mycontext = RequestContext(request)
    return render_to_response('sample_tracker/sample_detail.html',
                                {'sample': sample},
                              context_instance=mycontext)

    
def add_sample(request):
    """
    Add a new sample for a given user
    """
    myContext = RequestContext(request)
    if request.method == "POST":
        form = SampleForm(request.POST)
        if form.is_valid():
            #Create a new sample
            user = request.user
            chemical_formula = form.cleaned_data['chemical_formula']
            name = form.cleaned_data['name']
            msds =  form.cleaned_data['msds']
            mass = form.cleaned_data['mass']
            volume = form.cleaned_data['volume']
            bar_code = form.cleaned_data['bar_code']
            sample = Sample(user=user,
                            chemical_formula=chemical_formula,
                            name=name, 
                            msds=msds,
                            mass=mass,
                            volume=volume,
                            bar_code=bar_code)
            sample.save()
            return HttpResponseRedirect('/sample_list/')
    else:
        # Display empty form
        form = SampleForm()
    return render_to_response('sample_tracker/add_sample.html',
                               {"sample_form": form},
                               context_instance=myContext)
    
def list_samples(request):
    """
    Display available samples for a given user .
    Give an option add sample.
    """
    name = request.user.first_name
    
    if request.method != 'POST':
        sample = Sample()
    return render_to_response('sample_tracker/sample_list.html',
                               {'user_name': name,
                               'sample': sample})
